package latin.service.impl;

import latin.common.Const;
import latin.common.ServiceResponse;
import latin.common.TokenCache;
import latin.dao.UserMapper;
import latin.pojo.User;
import latin.service.IJavaService;
import latin.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    //用户注册
    public ServiceResponse<String> register(User user){
        //验证用户名是否存在
        ServiceResponse response = this.checkValid(user.getUsername(), Const.USERNAME);
        if(!response.isSuccess()){
            System.out.println(response.isSuccess());
            return response;
        }
        //验证电话是否存在
        response = this.checkValid(user.getPhone(),Const.PHONE);
        if(!response.isSuccess()){
            return response;
        }
        //设置此为普通用户

        user.setRole(Const.Role.ROLE_CUSTOMER);
        int resultCount = userMapper.insertSelective(user);
        if(resultCount > 0){
            return ServiceResponse.createBySuccess("注册成功");
        }
        return ServiceResponse.createByErrorMessage("注册失败");

    }
    //校验用户是否已经存在
    public ServiceResponse<String> checkValid(String str,String type){

        if (StringUtils.isNotBlank(type)) {
            //校验用户名是否存在
            if (Const.USERNAME.equals(type)) {
                int reslutCount = userMapper.checkUsername(str);
                if (reslutCount > 0) {
                    return ServiceResponse.createByErrorMessage("用户名已存在");
                }
            }
            //校验电话是否存在
            if (Const.PHONE.equals(type)) {
                int reslutCount = userMapper.checkPhone(type);
                if (reslutCount > 0) {
                    return ServiceResponse.createByErrorMessage("phone已存在");
                }
            }

        }else {
            return ServiceResponse.createByErrorMessage("参数错误");
        }
        return ServiceResponse.createBySuccessMessage("校验成功");
    }


    public ServiceResponse<User> login(String username,String password){
     int resultCount = userMapper.checkUsername(username);
     if(resultCount == 0){
         return ServiceResponse.createByErrorMessage("此用户名不存在");
     }
     User user = userMapper.selectByUsernamelogin(username,password);
     if(user == null){
         return ServiceResponse.createByErrorMessage("密码错误");
     }
     return ServiceResponse.createBySuccess("登录成功",user);
    }

    public ServiceResponse selectQuestion(String username){
        ServiceResponse response = this.checkValid(username,Const.USERNAME);
        if (response.isSuccess()){
            return ServiceResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestion(username);
        if(StringUtils.isBlank(question)){
            return ServiceResponse.createByErrorMessage("用户没有设置忘记密码的问题");
        }
        return ServiceResponse.createBySuccess();

    }

    public ServiceResponse<String> getAnswer(String  username,String question,String answer){
        int resultCount = userMapper.selectByUsernameQuestionAnswer(username,question,answer);
        if(resultCount > 0){
            //说明问题和答案是这个用户的，并且都是正确的
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServiceResponse.createBySuccess(forgetToken);
        }
        return ServiceResponse.createByErrorMessage("答案错误");
    }

    public ServiceResponse<String> forgetResetPassword(String username,String password,String forgetToken){
        if(StringUtils.isBlank(forgetToken)){
            return  ServiceResponse.createByErrorMessage("参数错误，token需要传递");
        }
        ServiceResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            return  ServiceResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isBlank(token)){
            return  ServiceResponse.createByErrorMessage("token无效或过期");
        }
        if(StringUtils.equals(forgetToken,token)){
            int rowCount = userMapper.updatePasswordByUsername(username,password);
            if(rowCount > 0){
                return  ServiceResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServiceResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServiceResponse.createByErrorMessage("修改密码失败");
    }
    public ServiceResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
        //防止横向越权，要校验一下用户的旧密码，一定要指定是这个用户，因为我们会查询一个人count（1），如果不指定id，那么结果就是true啦count>0
        int resultCount = userMapper.checkPassword(passwordOld,user.getId());
        if(resultCount == 0){
            return  ServiceResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(passwordNew);
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServiceResponse.createBySuccessMessage("密码更新成功");
        }
        return  ServiceResponse.createByErrorMessage("密码更新失败");
    }
}
